package com.haina.shop.controller.tzuser;

import com.haina.shop.constant.JwtClaimsConstant;
import com.haina.shop.constant.MessageConstant;
import com.haina.shop.dto.UserRegisterDTO;
import com.haina.shop.properties.JwtProperties;
import com.haina.shop.result.ServiceResult;
import com.haina.shop.service.UserService;
import com.haina.shop.utils.JwtUtil;
import com.haina.shop.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 用户注册
     * @param dto
     */
    @PostMapping("/register")
    public ServiceResult register(@RequestBody UserRegisterDTO dto){
          String userId=service.register(dto);
          if("fail".equals(userId)){
             return ServiceResult.error(MessageConstant.ERROR_CODE,MessageConstant.REGISTER_FAIL);
          }else{
              //成功
              //登录成功后，生成jwt令牌
              Map<String, Object> claims = new HashMap<>();
              claims.put(JwtClaimsConstant.user_ID, userId);
              String token = JwtUtil.createJWT(
                      jwtProperties.getUserSecretKey(),
                      jwtProperties.getUserTtl(),
                      claims);
              //创建登录成功返回的实体
              LoginVO loginVO = new LoginVO(token,token,jwtProperties.getUserTtl());
              return ServiceResult.LoginSuccess(loginVO);
          }
    }
}
